<template>
	<div class="list-box">
		<div class="pannel-title pannel-between">
			<div>新增工具</div>
		</div>
		<div class="line"></div>
		<div class="data-table">
			<div class="pannel-form">
				<a-form ref="form1" :model="formState" :rules="rules" :labelCol="{ span: 6, offset: 0 }">
					<a-form-item label="工具名称" name="name">
						<a-input v-model:value="formState.name" placeholder="请输入工具名称" />
					</a-form-item>
					<a-form-item label="工具分类" name="cateId">
						<a-select v-model:value="formState.cateId" :options="cateIds" placeholder="请选择工具分类"></a-select>
					</a-form-item>
					<a-form-item label="下载地址" name="url">
						<a-input v-model:value="formState.url" placeholder="请输入下载地址" />
					</a-form-item>
					<a-form-item label="排序序号" name="displayPriority">
						<a-input v-model:value="formState.displayPriority" placeholder="请输入大于等于0的正整数">
							<template #suffix>
								<a-tooltip title="排序序号数值越小越靠前">
									<info-circle-outlined style="color: rgba(255, 0, 0, 0.7)" />
								</a-tooltip>
							</template>
						</a-input>
					</a-form-item>
					<a-form-item label="简介" name="desc">
						<a-textarea v-model:value="formState.desc" placeholder="请输入工具的简介" :auto-size="{ minRows: 2, maxRows: 5 }" />
					</a-form-item>
					<a-form-item label="logo" name="logo">
						<avatar-upload v-model:value="formState.logo"></avatar-upload>
						<a @click="showPicModal()">使用历史图片</a>
					</a-form-item>
					<a-form-item label="工具文件压缩包" name="file">
						<file-upload v-model:value="formState.file"></file-upload>
					</a-form-item>
				</a-form>
				<a-modal width="700px" title="历史图片" v-model:visible="visiblePic" :maskClosable="false" :footer="null" :afterClose="closePicModal">
					<a-table :columns="columnsPic" :row-key="(record) => record.id" :scroll="{ x: 600, y: 400 }" :data-source="dataSourcePic" :pagination="pagesPic" :loading="picLoading" @change="changePagePic">
						<template #logo="{ text }">
							<img style="width:100px;height:100px;border-radius:4px;" :src="text" />
						</template>
						<template #action="{ record }">
							<a @click="selectPic(record.logo)">使用图片</a>
						</template>
					</a-table>
				</a-modal>
			</div>
			<div class="pannel-form-btn">
				<a-button type="default" shape="round" @click="cancel()">取消</a-button>
				<a-button :loading="btnLoading" type="primary" shape="round" @click="confirm()">确定</a-button>
			</div>
		</div>
	</div>
</template>
<script>
import { InfoCircleOutlined } from "@ant-design/icons-vue";
import { useStore } from "vuex";
import { ref,reactive } from "@vue/reactivity";
import { message, Button, Form, Input, Tooltip, Select, Modal, Table } from "ant-design-vue";
import httpRequest from "@/util/httpRequest";
import baseUtil from "@/util/baseUtil";
import avatarUpload from "@/components/avatarUpload";
import fileUpload from "@/components/fileUpload";
export default {
	components: {
		InfoCircleOutlined,
		AButton: Button,
		AForm: Form,
		AFormItem: Form.Item,
		AInput: Input,
		AModal:Modal,
		ATable:Table,
		ATextarea: Input.TextArea,
		ATooltip: Tooltip,
		ASelect: Select,
		avatarUpload,
		fileUpload
	},
	setup() {
		const store = useStore();
		//text：页面头部面包屑的显示文字，isBack：是否显示页面头部返回按钮
		const formState = ref({
			id: "",
			name: "",
			displayPriority: "",
			cateId: "",
			logo: "",
			url: "",
			file:"",
			desc: "",
		});
		const dataSourcePic = ref([]);
		const columnsPic = reactive([
			{
				title: "工具名称",
				dataIndex: "name",
				key: "name",
			},
			{
				title: "LOGO",
				dataIndex: "logo",
				key: "logo",
                width:240,
				slots: { customRender: "logo" },
			},
			{
				title: "操作",
				key: "action",
                width:100,
				slots: { customRender: "action" },
			},
		]);
		const pagesPic = ref({
			current: 1,
            pageSize: 10,
            total: 0,
		});
		return {
			formState,
			btnLoading: ref(false),
			cateIds: ref([]),
			store,
			dataSourcePic,
            columnsPic,
            pagesPic,
            picLoading:ref(false),
			visiblePic:ref(false),
		};
	},
	data() {
		return {
			rules: {
				name: {
					required: true,
					message: "不能为空",
					trigger: "blur",
				},
				cateId: {
					required: true,
					message: "不能为空",
					trigger: "change",
					type: "number",
				},
				logo: {
					required: true,
					message: "不能为空",
					trigger: "change",
				},
				file: {
					validator: this.requireFileOrUrl,
					trigger: 'change'
				},
				url: [
					{
						validator: this.requireFileOrUrl,
						trigger: "change",
					},
					{
						trigger: "blur",
						message: "请输入正确的URL地址",
						pattern: /^((ht|f)tps?):\/\/([\w-]+(\.[\w-]+)*\/?)+(\?([\w\-\\.,@?^=%&:\\/~\\+#]*)+)?$/,
					},
				],
				desc: {
					required: true,
					message: "不能为空",
					trigger: "blur",
				},
				displayPriority: [
					{
						required: true,
						message: "不能为空",
						trigger: "blur",
					},
					{
						trigger: "blur",
						message: "请输入大于等于0的整数",
						pattern: /^(0|[1-9]\d*)$/,
					},
				],
			},
		};
	},
	mounted() {
		this.store.dispatch("setBreadcrumb", {
			text: "工具管理 / 新增工具",
			isBack: false,
		});
		if(this.$route.query.id){
			httpRequest.post("获取工具详情",{id:this.$route.query.id}).then(res=>{
				this.formState = {...baseUtil.LineToHump(res.data)};
				this.formState.displayPriority = String(this.formState.displayPriority);
			})
			this.store.dispatch("setBreadcrumb", {
			text: "工具管理 / 编辑工具",
			isBack: false,
		});
		}
		httpRequest.post("获取工具分类集合(用于选择框)", {}).then((res) => {
			this.cateIds = res.data.map((e) => {
				return { value: e.id, label: e.name };
			});
		});
	},
	methods: {
		confirm() {
			this.$refs.form1.validate().then(() => {
				this.btnLoading = true;
				const url = this.formState.id ? "编辑工具" : "创建工具";
				const msg = this.formState.id ? "修改成功" : "创建成功";
				this.formState.url = this.formState.url || '';
				this.formState.file = this.formState.file || '';
				httpRequest
					.post(url, this.formState)
					.then(() => {
						this.visible = false;
						this.$router.push("/toolList");
						message.success(msg);
					})
					.finally(() => {
						this.btnLoading = false;
					});
			});
		},
		cancel(){
			this.$router.back();
		},
		async requireFileOrUrl(){
			if (this.formState.url || this.formState.file) {
				return Promise.resolve();
			} else {
				return Promise.reject("请填写下载地址或上传工具包");
			}
		},
		closePicModal(){
            this.visiblePic = false;
        },
        changePagePic(e){
            this.pagesPic.current = e.current;
			this.getList();
        },
        showPicModal(){
			console.log(1);
            this.pagesPic.current = 1;
            this.getList();
            this.visiblePic = true;
        },
        selectPic(imgUrl){
            this.formState.logo = imgUrl;
            this.visiblePic = false;
        },
		getList() {
			this.picLoading = true;
			httpRequest
				.post("获取工具列表",{...this.pagesPic,page:this.pagesPic.current})
				.then((res) => {
					this.dataSourcePic = res.data.data;
					this.pagesPic.total = res.data.total;
				})
				.finally(() => {
					this.picLoading = false;
				});
		},
	},
};
</script>
<style lang="less" scoped>
.line {
	width: 100%;
	margin: 20px 0;
	border-top: 1px solid #eee;
}
</style>
